package com.vehiclemanagement.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;  //IPage：分页数据接口（分页），获取一个数据当前页的对象
import com.vehiclemanagement.entity.Binding;          //Binding：绑定关联实体类
import com.vehiclemanagement.service.BindingService;  //BindingService：绑定关联服务接口
import com.vehiclemanagement.util.R;                  //R：统一响应封装类
import org.springframework.beans.factory.annotation.Autowired;   //Autowired：自动装配注解，用于将Spring容器中的Bean注入到当前类中
import org.springframework.web.bind.annotation.*;    //@RestController：表示这是一个RESTful风格的控制器，返回的数据直接作为响应体，不进行视图解析

import java.util.Date;    //Date：日期类，用于表示日期和时间    
import java.util.HashMap; //HashMap：哈希表，用于存储键值对
import java.util.Map;     //Map：映射接口，用于存储键值对

/**
 * 绑定关联控制器
 */
@RestController   //表示这是一个RESTful风格的控制器，返回的数据自动转换为JSON格式，直接作为响应体，不进行视图解析
@RequestMapping("/binding")  //表示这个控制器处理所有/binding请求
public class BindingController {
    
    @Autowired
    private BindingService bindingService;
    
    /**
     * 分页查询绑定关联列表
     */
    @GetMapping("/list")
    public R<IPage<Binding>> list(
        @RequestParam(value = "current", defaultValue = "1") Integer current,
        @RequestParam(value = "size", defaultValue = "10") Integer size,
        @RequestParam(value = "plateNumber", required = false) String plateNumber,
        @RequestParam(value = "driverName", required = false) String driverName,
        @RequestParam(value = "fuelCardNumber", required = false) String fuelCardNumber,
        @RequestParam(value = "etcCardNumber", required = false) String etcCardNumber,
        @RequestParam(value = "vehicleId", required = false) Long vehicleId,
        @RequestParam(value = "driverId", required = false) Long driverId,
        @RequestParam(value = "status", required = false) Integer status,
        @RequestParam(value = "sortField", required = false) String sortField,
        @RequestParam(value = "sortOrder", required = false) String sortOrder) {
    
        IPage<Binding> page = bindingService.pageBindings(
            current, size, plateNumber, driverName, fuelCardNumber, etcCardNumber,
            vehicleId, driverId, status, sortField, sortOrder
        );
        return R.ok(page);
    }
    
    /**
     * 获取绑定关联详情
     */
    @GetMapping("/{id}")
    public R<Binding> getById(@PathVariable Long id) {
        Binding binding = bindingService.getBindingById(id);
        if (binding == null) {
            return R.error("绑定关联不存在");
        }
        return R.ok(binding);
    }
    
    /**
     * 添加绑定关联
     */
    @PostMapping
    public R<Boolean> add(@RequestBody Binding binding) {
        System.out.println("接收到添加绑定关联请求，数据：" + binding);
        
        // 检查必要字段
        if (binding.getVehicleId() == null) {
            return R.error("车辆ID不能为空");
        }
        if (binding.getDriverId() == null) {
            return R.error("驾驶员ID不能为空");
        }
        
        // 检查是否已存在有效的绑定关系
        if (bindingService.existsActiveBinding(binding.getVehicleId(), binding.getDriverId(), 
                binding.getFuelCardId(), binding.getEtcCardId())) {
            return R.error("添加失败：相同的绑定关系已存在");
        }
        
        boolean result = bindingService.addBinding(binding);
        if (result) {
            return R.ok(true);
        } else {
            System.out.println("添加绑定关联失败，服务层返回false");
            return R.error("添加失败，请检查绑定关系是否已存在");
        }
    }
    
    /**
     * 更新绑定关联
     */
    @PutMapping
    public R<Boolean> update(@RequestBody Binding binding) {
        if (binding.getId() == null) {
            return R.error("绑定关联ID不能为空");
        }
        boolean result = bindingService.updateBinding(binding);
        return result ? R.ok(true) : R.error("更新失败");
    }
    
    /**
     * 删除绑定关联
     */
    @DeleteMapping("/{id}")
    public R<Boolean> delete(@PathVariable Long id) {
        System.out.println("接收到删除绑定关联请求，ID: " + id);
        
        boolean result = bindingService.deleteBinding(id);
        
        if (result) {
            System.out.println("成功删除绑定关联，ID: " + id);
            return R.ok(true);
        } else {
            System.out.println("删除绑定关联失败，ID: " + id);
            return R.error("删除失败");
        }
    }
    
    /**
     * 解绑关联
     */
    @PutMapping("/unbind/{id}")
    public R<Boolean> unbind(@PathVariable Long id) {
        System.out.println("接收到解绑关联请求，ID: " + id);
        
        Binding binding = bindingService.getBindingById(id);
        if (binding == null) {
            return R.error("绑定关联不存在");
        }
        
        binding.setStatus(0); // 设置为解绑状态
        binding.setUpdateTime(java.time.LocalDateTime.now());
        
        boolean result = bindingService.updateBinding(binding);
        return result ? R.ok(true) : R.error("解绑失败");
    }
    
    /**
     * 测试接口
     */
    @GetMapping("/test")
    public R<Object> test() {
        System.out.println("收到前端API测试请求");
        
        // 测试数据库连接
        try {
            long count = bindingService.count();
            System.out.println("数据库连接测试 - 绑定记录总数: " + count);
            
            // 返回更详细的测试信息
            Map<String, Object> data = new HashMap<>();
            data.put("message", "绑定关联API正常运行！");
            data.put("timestamp", new Date());
            data.put("dbConnected", true);
            data.put("totalRecords", count);
            
            return R.ok(data);
        } catch (Exception e) {
            System.err.println("数据库连接测试失败: " + e.getMessage());
            e.printStackTrace();
            
            Map<String, Object> data = new HashMap<>();
            data.put("message", "API可访问但数据库连接失败！");
            data.put("error", e.getMessage());
            data.put("timestamp", new Date());
            data.put("dbConnected", false);
            
            return R.ok(data);
        }
    }
    
    /**
     * 检查车辆是否已绑定
     */
    @GetMapping("/check-vehicle")
    public R<Map<String, Object>> checkVehicleBinding(
            @RequestParam("vehicleId") Long vehicleId,
            @RequestParam(value = "excludeId", required = false) Long excludeId) {
        
        System.out.println("接收到检查车辆绑定请求: vehicleId=" + vehicleId + ", excludeId=" + excludeId);
        
        boolean exists = bindingService.isVehicleAlreadyBound(vehicleId, excludeId);
        
        Map<String, Object> result = new HashMap<>();
        result.put("exists", exists);
        result.put("vehicleId", vehicleId);
        
        System.out.println("车辆绑定检查结果: " + exists);
        
        return R.ok(result);
    }
} 